package winOrDie.map_editor;

import java.io.File;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;


import winOrDie.graphics.maps.Map_Board;
import winOrDie.graphics.maps.WoD_Map;
import winOrDie.graphics.maps.WoD_Map_Editor;
import winOrDie.graphics.maps.Map_Cell.Map_Cell_Type;
import winOrDie.map_editor.Composite_Map_Editor_Table.Listener_Map_Editor_Table;
import winOrDie.map_editor.Event_Map_Editor_Table.Event_Type_Map_Editor_Table;




public class Shell_Map_Editor {

	private Shell sShell = null;  //  @jve:decl-index=0:visual-constraint="10,10"
	private Composite_Map_Editor_Table composite_Map_Editor = null;
	private Display display = null;
	
	
	public static class RGB_DATA
	{
		public static RGB rgb_Corridor = new RGB(179, 204, 179);
		public static RGB rgb_Wall = new RGB(0, 51, 102);
		public static RGB rgb_Pirates_Room = new RGB(219, 219, 0);
		public static RGB rgb_Tower = new RGB(87, 255, 255);
		public static RGB rgb_Tower_Door = new RGB(194, 71, 71);
		public static RGB rgb_Exit = new RGB(71, 117, 255);
	}
	

	
	
	/**
	 * This method initializes sShell
	 */
	private void createSShell() {
		display = Display.getCurrent();
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;
		sShell = new Shell(display);
		sShell.setText("Shell");
		sShell.setLayout(gridLayout);
		sShell.setSize(new Point(588, 270));
		
		create_Menu_Bar();
		new_WoD_Map();
		createComposite_Map_Editor();
		
		brush_Selected = Map_Cell_Type.Corridor;
		paint_WoD_Map();
		
	}

	/**
	 * This method initializes composite_Map_Editor	
	 *
	 */
	private void createComposite_Map_Editor() {
		GridData gridData = new GridData();
		gridData.grabExcessVerticalSpace = true;
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.CENTER;
		gridData.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
		composite_Map_Editor = new Composite_Map_Editor_Table(sShell, SWT.NONE);
		composite_Map_Editor.setLayoutData(gridData);
		
		
		
				
		composite_Map_Editor.add_Listener_Map_Editor_Table(new Listener_Map_Editor_Table() {
			
			@Override
			public void handleEvent(Event event) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void on_Event_Map_Editor_Table(
					Event_Map_Editor_Table eventMapEditorTable) {
				
				if (eventMapEditorTable.getEvent_Type() == Event_Type_Map_Editor_Table.Cell_Clicked)
				{
					//System.out.println("clicked on " + eventMapEditorTable.getPoint_Cell_Selected().x + " " + eventMapEditorTable.getPoint_Cell_Selected().y);
					
					int x_chord = eventMapEditorTable.getPoint_Cell_Selected().x;
					int y_chord = eventMapEditorTable.getPoint_Cell_Selected().y;
					
					composite_Map_Editor.set_Cell_Color(
							x_chord, 
							y_chord, 
							rgb_selected);
					
					try {
						woDMap.getMapBoard().get_Map_Cell(x_chord, y_chord).setType(brush_Selected);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						show_MessageBoxError(e.getMessage());
					}
					
/*					composite_Map_Editor.set_Cell_Image(
							eventMapEditorTable.getPoint_Cell_Selected().x, 
							eventMapEditorTable.getPoint_Cell_Selected().y, 
							image_test);*/
				}
				
			}
		});
		
		try {
			composite_Map_Editor.set_Matrix_Size(
					woDMap.getMapBoard().getColumns(), 
					woDMap.getMapBoard().getRows());
			//sShell.pack();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			show_MessageBoxError(e.getMessage());
		}
		
		
	}

	private String fileName = null;
	private WoD_Map woDMap = null;  //  @jve:decl-index=0:
	private int brush_Selected = Map_Cell_Type.Corridor;
	private RGB rgb_selected = RGB_DATA.rgb_Corridor;  //  @jve:decl-index=0:
	private Color color = new Color(Display.getCurrent(), rgb_selected);
	
	
	private Menu menuBar = null;
	private Menu submenu_File = null;
	private Menu submenu_Brush = null;
	
	
	
	
	
	
	private void create_Menu_Bar()
	{
		/*
		 * Menu bar
		 */
		menuBar = new Menu(sShell, SWT.BAR);
		
		
		/*
		 * Submenu File
		 */
		MenuItem submenuItem_File = new MenuItem(menuBar, SWT.CASCADE);
		submenuItem_File.setText("Archivo");
		
		submenu_File = new Menu(submenuItem_File);
		
		/*
		 * New file push button
		 */
		MenuItem push_NewFile = new MenuItem(submenu_File, SWT.PUSH); 
		push_NewFile.setText("Nuevo");
		push_NewFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				new_WoD_Map();
				fileName = null;
				composite_Map_Editor.dispose();
				createComposite_Map_Editor();
			}
			
		});
		MenuItem separator = new MenuItem(submenu_File, SWT.SEPARATOR);
		
		
		/*
		 * Open file push button
		 */
		MenuItem push_OpenFile = new MenuItem(submenu_File, SWT.PUSH);
		push_OpenFile.setText("Abrir");
		push_OpenFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				load_Map_From_File();
			}
		});
		
		MenuItem separator2 = new MenuItem(submenu_File, SWT.SEPARATOR);
		
		
		/*
		 * Save file push button
		 */
		MenuItem push_SaveFile = new MenuItem(submenu_File, SWT.PUSH);
		push_SaveFile.setText("Guardar");
		push_SaveFile.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				save_Map_To_FileName();
			}
		});
		
		
		/*
		 * Save as file push button
		 */
		MenuItem push_SaveFile_As = new MenuItem(submenu_File, SWT.PUSH);
		push_SaveFile_As.setText("Guardar como");
		push_SaveFile_As.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				save_Map_As_FileName();
			}
		}); 
		
		MenuItem separator3 = new MenuItem(submenu_File, SWT.SEPARATOR);
		
		MenuItem push_Exit = new MenuItem(submenu_File, SWT.PUSH);
		push_Exit.setText("Salir");
		push_Exit.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				exit_Application();
			}
		}); 
		
		submenuItem_File.setMenu(submenu_File);
		
		
		
		
		
		
		/*
		 * Brushes Submenu
		 */
		MenuItem submenuItem_Brush = new MenuItem(menuBar, SWT.CASCADE);
		submenuItem_Brush.setText("Pincel");
		submenu_Brush = new Menu(submenuItem_Brush);
		
		
		/*
		 * Corridor brush radio button
		 */
		MenuItem radio_Corridor = new MenuItem(submenu_Brush, SWT.RADIO);
		radio_Corridor.setSelection(true);
		radio_Corridor.setText("Pasillo");
		
		Image image_Corridor = new Image(Display.getCurrent(), 20, 10);
		GC gc = new GC(image_Corridor);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Corridor);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
		
	    radio_Corridor.setImage(image_Corridor);
	    
	    radio_Corridor.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Corridor;
	    		rgb_selected = RGB_DATA.rgb_Corridor;
	    	}
		});
	    
	    
	    /*
		 * Wall brush radio button
		 */
	    MenuItem radio_Wall = new MenuItem(submenu_Brush, SWT.RADIO);
	    radio_Wall.setText("Pared");
	    
	    Image image_Wall = new Image(Display.getCurrent(), 20, 10);
		gc = new GC(image_Wall);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Wall);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
	    
	    radio_Wall.setImage(image_Wall);
	    
	    radio_Wall.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Wall;
	    		rgb_selected = RGB_DATA.rgb_Wall;
	    	}
		});
	    
	    
	    /*
		 * Pirates Room brush radio button
		 */
	    MenuItem radio_Pirates_Room = new MenuItem(submenu_Brush, SWT.RADIO);
	    radio_Pirates_Room.setText("Piratas");
	    
	    Image image_Pirates_Rom = new Image(Display.getCurrent(), 20, 10);
		gc = new GC(image_Pirates_Rom);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Pirates_Room);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
	    
	    radio_Pirates_Room.setImage(image_Pirates_Rom);
	    
	    radio_Pirates_Room.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Pirates_Room;
	    		rgb_selected = RGB_DATA.rgb_Pirates_Room;
	    	}
		});
	    
	    /*
		 * Tower brush radio button
		 */
	    MenuItem radio_Tower = new MenuItem(submenu_Brush, SWT.RADIO);
	    radio_Tower.setText("Torre");
	    
	    Image image_Tower = new Image(Display.getCurrent(), 20, 10);
		gc = new GC(image_Tower);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Tower);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
	    
	    radio_Tower.setImage(image_Tower);
	    
	    radio_Tower.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Tower;
	    		rgb_selected = RGB_DATA.rgb_Tower;
	    	}
		});
	    
	    /*
		 * Tower door brush radio button
		 */
	    MenuItem radio_Tower_Door = new MenuItem(submenu_Brush, SWT.RADIO);
	    radio_Tower_Door.setText("Puerta");
	    
	    Image image_Tower_Door = new Image(Display.getCurrent(), 20, 10);
	    gc = new GC(image_Tower_Door);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Tower_Door);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
	    
	    radio_Tower_Door.setImage(image_Tower_Door);
	    
	    radio_Tower_Door.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Tower_Door;
	    		rgb_selected = RGB_DATA.rgb_Tower_Door;
	    	}
		});
	    
	    /*
	     * Exit brush radio button 
	     */
	    MenuItem radio_Exit = new MenuItem(submenu_Brush, SWT.RADIO);
	    radio_Exit.setText("Salida");
	    
	    Image image_Exit = new Image(Display.getCurrent(), 20, 10);
	    gc = new GC(image_Exit);
		color = new Color(Display.getCurrent(), RGB_DATA.rgb_Exit);
	    gc.setBackground(color);
	    gc.fillRectangle(0,0,20,10);
	    gc.dispose();
	    
	    radio_Exit.setImage(image_Exit);
	    
	    radio_Exit.addSelectionListener(new SelectionAdapter() {
	    	public void widgetSelected(SelectionEvent e) {
	    		brush_Selected = Map_Cell_Type.Exit;
	    		rgb_selected = RGB_DATA.rgb_Exit;
	    	}
		});
	    
	    
		submenuItem_Brush.setMenu(submenu_Brush);
		
		
		sShell.setMenuBar(menuBar);
		
	}
	
	
	
	
	/**
	 * This private method generates a new Map
	 */
	private void new_WoD_Map()
	{
		woDMap = new WoD_Map();
		woDMap.setMapTitle("Win or Die test map");
		try {
			woDMap.setMapBoard(new Map_Board());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			show_MessageBoxError(e.getMessage());
		}
		
	}
	
	
	private void save_Map()
	{
      	/*
      	 * Save Win Or Die map into file
      	 */
		try {
			WoD_Map_Editor.save_WoD_Map_To_File(woDMap, fileName);
		} catch (Exception e) {
			e.printStackTrace();
			show_MessageBoxError(e.getMessage());
		}
	}
	
	
	private void save_Map_As_FileName()
	{
		String selected = null;
		FileDialog fd = new FileDialog(sShell, SWT.SAVE);
		fd.setText("Save");
		fd.setFilterPath("C:/");
		String[] filterExt = { "*.xml", "*.WoDX", "*.*" };
		fd.setFilterExtensions(filterExt);
		selected = fd.open();
		
		if (selected != null) {
			File file = new File(selected);
			
			/*
			 * If file exists show question to replace it
			 */
			if (file.exists()) {
				MessageBox messageBox = new MessageBox(sShell,
						SWT.ICON_QUESTION | 
						SWT.YES | 
						SWT.NO);
				messageBox.setMessage("¿Reemplazar fichero " + file.getName() + "?");
				messageBox.setText("Fichero exite");
				int response = messageBox.open();
				
				if (response == SWT.NO) {
					return;
				}
			}
		}
		else
		{
			return;
		}
		fileName = selected;
		save_Map();
		
	}
	
	
	
	
	
	private void save_Map_To_FileName()
	{
		/*
		 * If filename is not set... select filename
		 */
      	if (fileName == null) {

			save_Map_As_FileName();
			return;
		}
      	
      	save_Map();
	}
	
	
	private void load_Map_From_File()
	{
        FileDialog fd = new FileDialog(sShell, SWT.OPEN);
        fd.setText("Abrir");
        fd.setFilterPath("C:/");
        String[] filterExt = { "*.xml", "*.WoDX", "*.*" };
        fd.setFilterExtensions(filterExt);
        String selected = fd.open();
        
        if (selected != null)
        {
        	
        	try {
        		WoD_Map woDMap = new WoD_Map();
				woDMap = WoD_Map_Editor.get_WoD_Map_From_File(selected);
				fileName = selected; 
				this.woDMap = woDMap;
			} catch (Exception e) {
				e.printStackTrace();
				show_MessageBoxError(e.getMessage());
				return;
			}
			
			paint_WoD_Map();
        }
        
	}
	
	
	private void paint_WoD_Map()
	{
		for (int column = 0; column < woDMap.getMapBoard().getColumns(); column++) {
			for (int row = 0; row < woDMap.getMapBoard().getRows(); row++) {
				
				try {
					final int brush_type = woDMap.getMapBoard().get_Map_Cell(column, row).getType();
					
					switch (brush_type) {
					case Map_Cell_Type.Corridor:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Corridor);
						break;
					case Map_Cell_Type.Wall:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Wall);
						break;						
					case Map_Cell_Type.Pirates_Room:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Pirates_Room);
						break;
					case Map_Cell_Type.Tower:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Tower);
						break;
					case Map_Cell_Type.Tower_Door:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Tower_Door);
						break;
					case Map_Cell_Type.Exit:
						composite_Map_Editor.set_Cell_Color(column, row, RGB_DATA.rgb_Exit);
						break;
					default:
						Exception exception = new Exception("Tipo de casilla desconocido.");
						throw exception;
					}
				} catch (Exception e) {
					e.printStackTrace();
			        
					show_MessageBoxError(e.getMessage());
					return;
				}
				
			}
		}
	}
	
	private void show_MessageBoxError(String Error_Message)
	{
		MessageBox messageBox = new MessageBox(sShell, SWT.ICON_ERROR | SWT.OK);
		messageBox.setMessage(Error_Message);
		messageBox.setText("Se ha producido un error");
		messageBox.open();
	}
	
	private void exit_Application()
	{
		MessageBox messageBox = new MessageBox(sShell, SWT.ICON_QUESTION
	            | SWT.YES | SWT.NO);
	        messageBox.setMessage("¿Seguro que desea salir?");
	        messageBox.setText("Salir del editor");
	        int response = messageBox.open();
	        if (response == SWT.YES)
	        {
				composite_Map_Editor.dispose();
				sShell.dispose();
				display.dispose();
				System.exit(0);
	        }

	}
	
	
	public Shell_Map_Editor() {
		super();
		createSShell();
	}
	
	
	
	public void execute()
	{
		sShell.pack();
		sShell.open();
		while (!sShell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}

		}
		sShell.dispose();
	}
	
	
	public static void main(String[] args) {
		new Shell_Map_Editor().execute();
	}
	
	
	
	
	
	
	
	
	
	
}
